/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DAO.LoginDAO;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Login;
import model.Mensagem;

/**
 *
 * @author ASR Consultoria
 */
public class Controller_Login extends HttpServlet {

    public void cadastrar(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> obj = new ArrayList<Object>();
        Mensagem msg = new Mensagem();
        Gson gson = new Gson();

        Login login = new Login();
        LoginDAO loginDAO = new LoginDAO();

        login.setUsuario(request.getParameter("usuario"));
        login.setSenha(request.getParameter("senha"));
        System.out.println(request.getParameter("usuario") + " " + request.getParameter("senha") + " " + request.getParameter("adm"));
        login.setAdm(Boolean.parseBoolean(request.getParameter("adm")));
        try {
            loginDAO.criar(login);
            msg.setMensagem("Cadastro efetuado com sucesso!!!!");
            obj.add(msg);
            out.print(gson.toJson(obj));
        } catch (Exception e) {
            System.out.println("Erro ao cadastrar o login!!" + e.getMessage());
        }

    }

    public void listar(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Login> obj = new ArrayList<Login>();

        Mensagem objmsg = new Mensagem();

        Gson objJson = new Gson();
        try {
            LoginDAO loginDAO = new LoginDAO();
            System.out.println("teste");

            obj = loginDAO.buscarTodas(request.getParameter("texto"));
            out.print(objJson.toJson(obj));
        } catch (Exception e) {
            System.out.println("Erroooooooo" + e.getMessage());
        }

    }

    public void alterar(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            //criar um array list generico
            ArrayList<Object> arrobj = new ArrayList<Object>();

            Mensagem objmsg = new Mensagem();

            Gson objJson = new Gson();

            Login login = new Login();

            LoginDAO loginDAO = new LoginDAO();
            System.out.println("O número do id é: " + request.getParameter("id"));
            login.setId(Integer.parseInt(request.getParameter("id")));
            login.setSenha(request.getParameter("senha"));
            login.setAdm(Boolean.parseBoolean(request.getParameter("adm")));
            System.out.println(request.getParameter("senha") + " " + Boolean.parseBoolean(request.getParameter("adm")));
            System.out.println(request.getParameter("id"));

            loginDAO.atualizar(login);

            objmsg.setMensagem("Usuário alterado com sucesso!!!!");
            arrobj.add(objmsg);

            out.print(objJson.toJson(arrobj));
        } catch (Exception e) {
            System.out.println("errooooo!!!" + e.getMessage());

        }

    }

    public void buscar_por_id(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        PrintWriter out = response.getWriter();
        Gson objJson = new Gson();

        ArrayList<Login> arrobj = new ArrayList<Login>();

        LoginDAO loginDAO = new LoginDAO();

        try {
            arrobj.add(loginDAO.buscarLoginByCodigo(Integer.parseInt(request.getParameter("id"))));
            out.print(objJson.toJson(arrobj));

        } catch (ClassNotFoundException | NumberFormatException | SQLException e) {
            System.out.println("Ocorreu um erro ae!!!!" + e.getMessage());
        }

    }

    protected void efetuarLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, Exception {
        PrintWriter out = response.getWriter();

        Gson objJson = new Gson();
        LoginDAO loginDAO = new LoginDAO();
        System.out.println("Teste 111111");
        Mensagem msg = new Mensagem();
        ArrayList<Object> arrobj = new ArrayList<Object>();

        String usuario = request.getParameter("usuario");
        System.out.println(request.getParameter("usuario"));
        String senha = request.getParameter("senha");
        System.out.println(request.getParameter("senha"));

        Login login = new Login();

        try {
            login.setUsuario(usuario);
            login.setSenha(senha);
            Login novoLogin = new Login();
            novoLogin = loginDAO.login(login);

            if (novoLogin.getId() < 1) {
                System.out.println("id do usuário!!!!" + novoLogin.getId());
                throw new Exception("Usuário inválido!!!");
            } else {
                msg.setMensagem("Login efetuado com sucesso!!!!");
                arrobj.add(msg);
                arrobj.add(novoLogin);

                out.print(objJson.toJson(arrobj));

            }

        } catch (Exception e) {

            System.out.println("Erro ao efetuar o login!!!! " + e.getMessage());

        } finally {

        }
    }

    public void apagar(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            Gson objJson = new Gson();

            Mensagem msg = new Mensagem();

            ArrayList<Object> arrobj = new ArrayList<Object>();

            LoginDAO loginDAO = new LoginDAO();

            loginDAO.apagar(Integer.parseInt(request.getParameter("id")));

            msg.setMensagem("Usuário apagado com sucesso!!");

            out.print(objJson.toJson(msg));
        } catch (IOException | NumberFormatException | SQLException e) {
            System.out.println("Erro ao apagar usuário " + e.getMessage());
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int oper = Integer.parseInt(request.getParameter("oper"));
        try {
            switch (oper) {

                case 1:
                    cadastrar(request, response);
                    break;

                case 2:
                    listar(request, response);
                    break;

                case 3:
                    alterar(request, response);
                    break;

                case 4:
                    efetuarLogin(request, response);
                    break;

                case 5:
                    apagar(request, response);
                    break;
                case 6:
                    buscar_por_id(request, response);
                    break;
            }

        } catch (Exception e) {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
